import 'package:dss_base/ext/function_ext.dart';
import 'package:flutter/widgets.dart';

import '../dss_base.dart';

class NavigatorUtil {
  NavigatorUtil._();

  static CallbackX<Widget>? _loginPageCallback;
  static bool _isLogin = false;

  static void init({
    required CallbackX<Widget> loginPageCallback,
    required bool isLogin,
  }) {
    _loginPageCallback = loginPageCallback;
    _isLogin = isLogin;
  }

  static Future<T?>? pushLogin<T>() {
    CallbackX<Widget>? loginPage = _loginPageCallback;
    if (loginPage != null) {
      return _realPush(loginPage);
    }
    return null;
  }

  static Future<T?>? push<T>(
    CallbackX<Widget> pageCallback, {
    bool replace = false,
    bool clearStack = false,
    bool checkLogin = true,
  }) {
    if (checkLogin && !_isLogin) {
      return pushLogin();
    }
    return _realPush(pageCallback, replace: replace, clearStack: clearStack);
  }

  static Future<T?>? pushNamed<T>(
    String page, {
    bool replace = false,
    bool clearStack = false,
    bool checkLogin = false,
    dynamic arguments,
  }) {
    if (checkLogin && !_isLogin) {
      return pushLogin();
    }
    return _realPushNamed(
      page,
      replace: replace,
      clearStack: clearStack,
      arguments: arguments,
    );
  }

  /// 返回到上个界面
  /// result: 返回上个界面传递的数据
  static void back<T>({T? result}) {
    return Get.back(result: result);
  }

  static Future<T?>? _realPush<T>(
    CallbackX<Widget> pageCallback, {
    bool replace = false,
    bool clearStack = false,
    dynamic arguments,
  }) {
    if (replace) {
      return _off(pageCallback);
    } else if (clearStack) {
      return _offAll(pageCallback);
    } else {
      return _to(pageCallback);
    }
  }

  static Future<T?>? _realPushNamed<T>(
    String page, {
    bool replace = false,
    bool clearStack = false,
    dynamic arguments,
  }) {
    if (replace) {
      return _offNamed(page);
    } else if (clearStack) {
      return _offAllNamed(page);
    } else {
      return _toNamed(page);
    }
  }

  /// 跳转到某个界面
  static Future<T?>? _to<T>(CallbackX<Widget> pageCallback) {
    return Get.to(pageCallback);
  }

  /// 跳转到某个界面
  static Future<T?>? _toNamed<T>(String page) {
    return Get.toNamed(page);
  }

  /// 跳转到某个界面，并关闭当前界面
  static Future<T?>? _off<T>(CallbackX<Widget> pageCallback) {
    return Get.off(pageCallback);
  }

  /// 跳转到某个界面，并关闭当前界面
  static Future<T?>? _offNamed<T>(String page) {
    return Get.offNamed(page);
  }

  /// 跳转到某个界面，并关闭所有界面
  static Future<T?>? _offAll<T>(dynamic page) {
    return Get.offAll(() => page);
  }

  /// 跳转到某个界面，并关闭所有界面
  static Future<T?>? _offAllNamed<T>(String newRouteName) {
    return Get.offAllNamed(newRouteName);
  }
}
